import axios from 'axios'
import {MessageBox, Message} from 'element-ui'
import store from '@/store'
import {getSotrageToken} from '@/utils/storage'

// 创建 axios 实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  timeout: 5000 // request timeout
})

// 请求拦截 request interceptor
service.interceptors.request.use(
  config => {
    //本地 token 存在，则请求头携带该 token
      let token = store.getters.token || getSotrageToken()
    if (token) {
      config.headers['token'] = token //
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截 response interceptor
service.interceptors.response.use(
  response => {
    let result = response.data  // 设置相应返回数据
    //console.log(result);  //调式输出

    //处理返回结果
    if (result.code !== 200) {
      Message({
        message: result.message || 'Error',
        type: 'error',
        duration: 3 * 1000
      });
      // 401: Illegal token;
      if (result.code === 401) {
        // to re-login
        MessageBox.confirm('需要重新登录', '确认登录', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(result.message || 'Error'))

    } else {
      //return result
      return Promise.resolve(result)
    }
  },
  error => {
    console.log('request.js ERROR:' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
